import React, { useState, useRef } from 'react';
import { View, Text, SafeAreaView, TextInput, TouchableOpacity, Image, Modal, ScrollView, Alert } from 'react-native';
import { Toast } from '@ant-design/react-native';
import Header from '../../../components/Header';
import CustomQRScanner from '../../../components/CustomQRScanner';
import { scanMesMBomToolsClaimList, claimMaterial } from './api';
import saoma from '../../../assets/saoma.png';
import { styles } from './styles';

interface PickingProps {
    onNavigateToLogin?: () => void;
    onBackPress?: () => void;
}

const Picking: React.FC<PickingProps> = ({ onNavigateToLogin, onBackPress }) => {
    const [workOrderNumber, setWorkOrderNumber] = useState('');
    const [shelfNumber, setShelfNumber] = useState('');
    const [storageLocation, setStorageLocation] = useState('');
    const [workOrderScanVisible, setWorkOrderScanVisible] = useState(false);
    const [shelfScanVisible, setShelfScanVisible] = useState(false);
    const [storageScanVisible, setStorageScanVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const [toolsList, setToolsList] = useState<any[]>([]);
    const [workOrderData, setWorkOrderData] = useState<any>(null);
    const [selectedMaterials, setSelectedMaterials] = useState<any[]>([]);

    // 工装编号输入框的引用
    const shelfInputRef = useRef<TextInput>(null);
    // 储位编号输入框的引用
    const storageInputRef = useRef<TextInput>(null);

    // 扫描工单
    const handleWorkOrderScan = () => {
        setWorkOrderScanVisible(true);
    };

    // 扫描工装编号
    const handleShelfScan = () => {
        setShelfScanVisible(true);
    };

    // 扫描储位编号
    const handleStorageScan = () => {
        setStorageScanVisible(true);
    };

    // 处理工单扫描结果
    const handleWorkOrderScanResult = async (data: string) => {
        setWorkOrderScanVisible(false);
        setWorkOrderNumber(data);
        await handleWorkOrderSubmit(data);
    };

    // 处理工装编号扫描结果
    const handleShelfScanResult = async (data: string) => {
        setShelfScanVisible(false);
        // 处理二维码格式，获取#后面的内容（去掉#前面的部分）
        const processedData = data.includes('#') ? data.split('#')[1] : data;
        setShelfNumber(processedData);

        // 自动提交工装编号，添加到已选列表
        await handleShelfSubmit(processedData);

        // 扫描完成后重置输入框，保持焦点状态
        setTimeout(() => {
            setShelfNumber('');
            // 重新聚焦到输入框
            shelfInputRef.current?.focus();
        }, 500);
    };

    // 处理储位编号扫描结果
    const handleStorageScanResult = async (data: string) => {
        setStorageScanVisible(false);
        // 处理二维码格式，获取#后面的内容（去掉#前面的部分）
        const processedData = data.includes('#') ? data.split('#')[1] : data;
        setStorageLocation(processedData);
    };

    // 提交工单
    const handleWorkOrderSubmit = async (value: string) => {
        if (!value.trim()) return;

        setLoading(true);
        try {
            const response = await scanMesMBomToolsClaimList({ qr_code: value });
            console.log('工单扫描成功:', response);

            if (response.code === 200 && response.data) {
                setWorkOrderData(response.data);
                // 提取工装列表数据
                const tools = response.data.list || [];
                const allTools: any[] = [];

                tools.forEach((item: any) => {
                    if (item.tools_list && Array.isArray(item.tools_list)) {
                        item.tools_list.forEach((tool: any) => {
                            allTools.push({
                                ...tool,
                                toolsModel: item.tools_model, // 工装型号
                                totalQuantity: item.quantity, // 总需求数量
                                isOk: item.is_ok, // 是否可用
                            });
                        });
                    }
                });

                setToolsList(allTools);

                // 检查是否有可用的工装
                if (allTools.length === 0) {
                    Toast.info('没有足够的工装', 2);
                    // 清空工单相关数据
                    setWorkOrderNumber('');
                    setWorkOrderData(null);
                    setToolsList([]);
                    setSelectedMaterials([]);
                    setStorageLocation('');
                }
            }
        } catch (error) {
            console.error('工单扫描失败:', error);
            // 这里可以添加错误提示
        } finally {
            setLoading(false);
        }
    };

    // 提交工装编号 - 不再调用接口，直接添加到已选列表
    const handleShelfSubmit = async (value: string) => {
        if (!value.trim()) return;

        // 检查是否已经扫描了工单
        if (!workOrderData) {
            Toast.info('请先扫描工单', 1.5);
            return;
        }

        // 检查是否已经选择过该工装
        const existingIndex = selectedMaterials.findIndex(
            item => item.tools_num === value
        );

        if (existingIndex === -1) {
            // 添加新工装到已选列表，包含完整的工装信息
            const newMaterial = {
                id: Date.now(), // 使用时间戳作为临时ID
                tools_num: value, // 工装编号
                num: '', // 数量，暂时为空
                batch_order_num: workOrderData.batch_order_num || '', // 批次号
                mbom_num: workOrderData.mbom_num || '' // MBOM号
            };
            console.log('添加新工装:', newMaterial);
            setSelectedMaterials(prev => [...prev, newMaterial]);
            // Toast.success('工装添加成功', 1.5);
        } else {
            // 如果已存在，提示用户
            Toast.info('该工装已选择', 1.5);
        }
    };

    // 工单输入框回车处理
    const handleWorkOrderSubmitEditing = () => {
        handleWorkOrderSubmit(workOrderNumber);
    };

    // 工装编号输入框回车处理
    const handleShelfSubmitEditing = () => {
        const currentValue = shelfNumber;
        // 处理输入内容，去掉#前面的部分
        const processedValue = currentValue.includes('#') ? currentValue.split('#')[1] : currentValue;
        handleShelfSubmit(processedValue);
        // 手动输入完成后也重置输入框，保持焦点状态
        setTimeout(() => {
            setShelfNumber('');
            // 重新聚焦到输入框
            shelfInputRef.current?.focus();
        }, 500);
    };

    // 储位编号输入框回车处理
    const handleStorageSubmitEditing = () => {
        const currentValue = storageLocation;
        // 处理输入内容，去掉#前面的部分
        const processedValue = currentValue.includes('#') ? currentValue.split('#')[1] : currentValue;
        console.log('储位编号输入:', processedValue);
        // 不清空输入框，保持用户输入的内容
    };



    // 删除已选工装
    const handleDeleteMaterial = (index: number) => {
        Alert.alert(
            '确认删除',
            '确定要删除这个工装吗？',
            [
                { text: '取消', style: 'cancel' },
                {
                    text: '确定',
                    onPress: () => {
                        setSelectedMaterials(prev => prev.filter((_, i) => i !== index));
                    }
                }
            ]
        );
    };

    // 领用工装提交
    const handleClaimSubmit = async () => {
        // 检查是否已经输入或扫描了工单
        if (!workOrderNumber.trim()) {
            Toast.info('请输入或扫描工单', 1.5);
            return;
        }

        // 检查是否已经扫描了工单
        if (!workOrderData) {
            Toast.info('请先扫描工单', 1.5);
            return;
        }

        if (selectedMaterials.length === 0) {
            Toast.info('请先选择要领用的工装', 1.5);
            return;
        }

        // 调试：显示当前已选工装的完整数据结构
        console.log('当前已选工装列表:', selectedMaterials);
        console.log('工单数据:', workOrderData);

        setLoading(true);
        try {
            // 构建领用工装数据，确保包含所有必要字段
            const claimData = selectedMaterials.map(material => ({
                tools_num: material.tools_num,
                shelf_num: storageLocation || '', // 使用当前输入的储位值
                num: material.num || '',
                batch_order_num: material.batch_order_num,
                mbom_num: material.mbom_num
            }));

            console.log('领用工装接口 - 提交参数:', claimData);
            const response = await claimMaterial(claimData);

            if (response.code === 200) {
                Toast.success('领用工装成功', 1.5);
                // 清空已选工装列表
                setSelectedMaterials([]);
                // 清空工单数据
                setWorkOrderData(null);
                setToolsList([]);
                setWorkOrderNumber('');
                // 清空储位编号
                setStorageLocation('');
            } else {
                Toast.fail(response.msg || '领用工装失败', 1.5);
            }
        } catch (error) {
            console.error('领用工装失败:', error);
            Toast.fail('领用工装失败，请重试', 1.5);
        } finally {
            setLoading(false);
        }
    };

    return (
        <SafeAreaView style={styles.container}>
            <Header
                title="领用工装"
                showBackButton={true}
                onNavigateToLogin={onNavigateToLogin}
                onBackPress={onBackPress}
            />
            <View style={styles.content}>
                <ScrollView style={styles.scrollContent} showsVerticalScrollIndicator={false}>
                    {/* 工单扫描区域 */}
                    <View style={styles.scanSection}>
                        <Text style={styles.sectionTitle}>工单扫描</Text>
                        <View style={styles.inputRow}>
                            <View style={styles.inputContainer}>
                                <TextInput
                                    style={styles.input}
                                    placeholder="请输入工单号"
                                    placeholderTextColor="#999"
                                    value={workOrderNumber}
                                    onChangeText={setWorkOrderNumber}
                                    onSubmitEditing={handleWorkOrderSubmitEditing}
                                    returnKeyType="search"
                                />
                                {workOrderNumber.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.clearButton}
                                        onPress={() => {
                                            setWorkOrderNumber('');
                                            setToolsList([]);
                                            setWorkOrderData(null);
                                            setSelectedMaterials([]);
                                            setStorageLocation('');
                                        }}
                                    >
                                        <Text style={styles.clearButtonText}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                            <TouchableOpacity
                                style={styles.scanBtn}
                                onPress={handleWorkOrderScan}
                                disabled={loading}
                            >
                                <Image source={saoma} style={{ width: 30, height: 30 }} />
                            </TouchableOpacity>
                        </View>
                    </View>

                    {/* 可领用工装列表 */}
                    {toolsList.length > 0 && (
                        <View style={styles.materialListSection}>
                            <Text style={styles.sectionTitle}>可领用工装列表</Text>
                            {toolsList.map((tool: any, index: number) => (
                                <View key={index} style={styles.materialItem}>
                                    <View style={styles.materialDetails}>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>工装型号:</Text>
                                            <Text style={styles.detailValue}>{tool.toolsModel}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>工装编号:</Text>
                                            <Text style={styles.detailValue}>{tool.tools_num}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>储位:</Text>
                                            <Text style={styles.detailValue}>{tool.shelf_num}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>总需求数量:</Text>
                                            <Text style={styles.detailValue}>{tool.totalQuantity}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>状态:</Text>
                                            <Text style={styles.detailValue}>{tool.isOk ? '可用' : '不可用'}</Text>
                                        </View>
                                    </View>
                                </View>
                            ))}
                        </View>
                    )}

                    {/* 工装编号扫描区域 */}
                    <View style={styles.scanSection}>
                        <Text style={styles.sectionTitle}>工装编号</Text>
                        <View style={styles.inputRow}>
                            <View style={styles.inputContainer}>
                                <TextInput
                                    ref={shelfInputRef}
                                    style={styles.input}
                                    placeholder="请输入工装编号"
                                    placeholderTextColor="#999"
                                    value={shelfNumber}
                                    onChangeText={setShelfNumber}
                                    onSubmitEditing={handleShelfSubmitEditing}
                                    returnKeyType="search"
                                />
                                {shelfNumber.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.clearButton}
                                        onPress={() => {
                                            setShelfNumber('');
                                        }}
                                    >
                                        <Text style={styles.clearButtonText}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                            <TouchableOpacity
                                style={styles.scanBtn}
                                onPress={handleShelfScan}
                                disabled={loading}
                            >
                                <Image source={saoma} style={{ width: 30, height: 30 }} />
                            </TouchableOpacity>
                        </View>
                    </View>

                    {/* 已选工装列表 */}
                    {selectedMaterials.length > 0 && (
                        <View style={styles.selectedMaterialsSection}>
                            <Text style={styles.sectionTitle}>已选工装列表</Text>
                            {selectedMaterials.map((material, index) => (
                                <View key={index} style={styles.selectedMaterialItem}>
                                    <View style={styles.materialDetails}>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>工装编号:</Text>
                                            <Text style={styles.detailValue}>{material.tools_num}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>批次号:</Text>
                                            <Text style={styles.detailValue}>{material.batch_order_num}</Text>
                                        </View>
                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}>MBOM号:</Text>
                                            <Text style={styles.detailValue}>{material.mbom_num}</Text>
                                        </View>

                                        <View style={styles.detailRow}>
                                            <Text style={styles.detailLabel}></Text>
                                            <TouchableOpacity
                                                style={styles.deleteButton}
                                                onPress={() => handleDeleteMaterial(index)}
                                            >
                                                <Text style={styles.deleteButtonText}>删除</Text>
                                            </TouchableOpacity>
                                        </View>
                                    </View>
                                </View>
                            ))}
                        </View>
                    )}

                    {/* 储位编号扫描区域 */}
                    <View style={styles.scanSection}>
                        <Text style={styles.sectionTitle}>储位编号</Text>
                        <View style={styles.inputRow}>
                            <View style={styles.inputContainer}>
                                <TextInput
                                    ref={storageInputRef}
                                    style={styles.input}
                                    placeholder="请输入储位编号"
                                    placeholderTextColor="#999"
                                    value={storageLocation}
                                    onChangeText={setStorageLocation}
                                    onSubmitEditing={handleStorageSubmitEditing}
                                    returnKeyType="search"
                                />
                                {storageLocation.length > 0 && (
                                    <TouchableOpacity
                                        style={styles.clearButton}
                                        onPress={() => {
                                            setStorageLocation('');
                                        }}
                                    >
                                        <Text style={styles.clearButtonText}>×</Text>
                                    </TouchableOpacity>
                                )}
                            </View>
                            <TouchableOpacity
                                style={styles.scanBtn}
                                onPress={handleStorageScan}
                                disabled={loading}
                            >
                                <Image source={saoma} style={{ width: 30, height: 30 }} />
                            </TouchableOpacity>
                        </View>
                    </View>

                    {/* 工单扫码模态框 */}
                    <Modal visible={workOrderScanVisible} animationType="slide">
                        <CustomQRScanner
                            onRead={handleWorkOrderScanResult}
                            onClose={() => setWorkOrderScanVisible(false)}
                        />
                    </Modal>

                    {/* 工装编号扫码模态框 */}
                    <Modal visible={shelfScanVisible} animationType="slide">
                        <CustomQRScanner
                            onRead={handleShelfScanResult}
                            onClose={() => setShelfScanVisible(false)}
                        />
                    </Modal>

                    {/* 储位编号扫码模态框 */}
                    <Modal visible={storageScanVisible} animationType="slide">
                        <CustomQRScanner
                            onRead={handleStorageScanResult}
                            onClose={() => setStorageScanVisible(false)}
                        />
                    </Modal>

                    {/* 加载状态 */}
                    {loading && (
                        <View style={styles.loadingContainer}>
                            <Text style={styles.loadingText}>处理中...</Text>
                        </View>
                    )}
                </ScrollView>

                {/* 领用工装按钮 - 固定在底部，不参与滚动 */}
                <TouchableOpacity
                    style={[styles.claimButton, loading && styles.claimButtonDisabled]}
                    onPress={handleClaimSubmit}
                    disabled={loading}
                >
                    <Text style={styles.claimButtonText}>领用工装</Text>
                </TouchableOpacity>
            </View>
        </SafeAreaView>
    );
};

export default Picking; 